package com.jewaton.auth.commons.service.impl;

import com.jewaton.auth.commons.dao.MenuDAO;
import com.jewaton.auth.commons.entity.Menu;
import com.jewaton.auth.commons.service.MenuService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**   
 *    
 * 菜单表service实现类
 *
 */

@Service(value="menuService")
public class MenuServiceImpl implements MenuService {
	
	private static final int PC = 0;  // police
	private static final int PPL = 1;  // people
	
	@Resource(name="menuDAO")
	private MenuDAO menuDAO;

	public void setMenuDAO(MenuDAO menuDAO) {
		this.menuDAO = menuDAO;
	}
	
	@Override
	@Cacheable(value="menu", key="'pcmenu'+#aid")
	public List<Menu> getPcMenu(long aid) {
	      List<Menu> menus = menuDAO.findMenuByPcAccount(aid);
	        List<Menu> tree = new ArrayList<Menu>();
	        Map<Long, Menu> menuMap = new HashMap<Long, Menu>();
	        for(Menu m:menus){
	            if(!menuMap.containsKey(m.getMid()))
	                menuMap.put(m.getMid(), m);
	        }
	        for(Menu m:menus){
	            if(m.getParentId()!=null){
	                if(menuMap.containsKey(m.getParentId())){
	                    Menu parent=menuMap.get(m.getParentId());
	                    parent.getChildren().add(m);
	                }
	                if(m.getParentId().intValue()==0){
	                    tree.add(m);
	                }
	            }
	        }
	        return tree;
	}

	@Override
	public Menu findMenuById(long id) {
		return menuDAO.findMenuById(id);
	}
	
	@Override
	public List<Menu> getMenuTree() {
		List<Menu> menus = menuDAO.findAll();
		List<Menu> tree = new ArrayList<Menu>();
		Map<Long, Menu> menuMap = new HashMap<Long, Menu>();
		for(Menu m:menus){
			if(!menuMap.containsKey(m.getMid()))
				menuMap.put(m.getMid(), m);
		}
		for(Menu m:menus){
			if(m.getParentId()!=null){
				if(menuMap.containsKey(m.getParentId())){
					Menu parent=menuMap.get(m.getParentId());
					parent.getChildren().add(m);
				}
				if(m.getParentId().intValue()==0){
					tree.add(m);
				}
			}
		}
		return tree;
	}



	
	
	


	
	

}
